#include <dlfcn.h>
#include "CKRuleManage.h"



namespace K_Engine
{
	CKRuleManage* CKRuleManage::GetInstance()
	{
		static CKRuleManage __instance;
		return &__instance;
	}
	
	
	CKRuleManage::CKRuleManage(){}
	
	
	CKRuleManage::~CKRuleManage()
	{
		std::map<std::string, CKRule*>::iterator it;
		for(it = m_rule.begin(); m_rule.end() != it; it++)
		{
			delete static_cast<CKRule*>(it->second);
		}
		m_rule.clear();
	}
	
	
	void CKRuleManage::SetLastError(std::string strlasterror)
	{
		m_strLastError = strlasterror;
	}
	
	
	std::string CKRuleManage::strGetLastError()
	{
		return m_strLastError;
	}
	
	
	bool CKRuleManage::AddRule(std::string rule)
	{
		CKRule *_crule = new CKRule();
		if(!_crule->LoadLibrary(rule))
		{
			std::string temp = "加载规则 {";
			temp += rule + "} 失败";
			SetLastError(temp);
			delete _crule;
			return false;
		}
		else
		{
			m_rule.insert(std::pair<std::string, CKRule*>(_crule->GetRuleName(), _crule));
			return true;
		}
	}
	
	
	bool CKRuleManage::RemoveRule(std::string rule)
	{
		std::map<std::string, CKRule*>::iterator it;
		it = m_rule.find(rule);
		if(m_rule.end() != it)
		{
			delete static_cast<CKRule*>(it->second);
			m_rule.erase(it);
			return true;
		}
		else
		{
			std::string temp = "找不到规则(";
			temp += rule + ")，移除规则失败";
			SetLastError(temp);
			return false;
		}
	}
	
	
	CKRule* CKRuleManage::GetRuleObject(std::string rule)
	{
		std::map<std::string, CKRule*>::iterator it;
		it = m_rule.find(rule);
		if(m_rule.end() != it)
		{
			return static_cast<CKRule*>(it->second);
		}
		else
		{
			std::string temp = "找不到规则(";
			temp += rule + ")，获取规则失败";
			SetLastError(temp);
			return NULL;
		}
	}
}
